#include "loadingframe.h"
#include <QLabel>
#include <QTimer>
#include <QVBoxLayout>

namespace yc {

LoadingFrame::LoadingFrame(const QString& text, QWidget* parent)
    : LoadingFrame(text, QSize(30, 30), QString(":/images/loading/72px_%1.png"), 15, 0, 50, parent)
{
    setFocusPolicy(Qt::NoFocus);
    setAttribute(Qt::WA_TransparentForMouseEvents, false);
    setAttribute(Qt::WA_AlwaysStackOnTop, true);
}

LoadingFrame::LoadingFrame(const QString& text, const QSize& icon_size, const QString& path,
                           int count, int index_width, int interval, QWidget* parent)
    : QFrame(parent), path_(path), count_(count), index_width_(index_width), index_(0)
{
    setFocusPolicy(Qt::NoFocus);
    setAttribute(Qt::WA_TransparentForMouseEvents, false);

    QVBoxLayout* vl = new QVBoxLayout(this);
    vl->setContentsMargins(0, 0, 0, 0);
    vl->setSpacing(8);
    vl->addStretch(1);

    image_ = new QLabel(this);
    image_->setObjectName("img");
    image_->setAlignment(Qt::AlignCenter);
    image_->setScaledContents(true);
    image_->setFixedSize(icon_size);
    vl->addWidget(image_, 0, Qt::AlignHCenter);

    text_ = new QLabel(text, this);
    text_->setObjectName("text");
    text_->setAlignment(Qt::AlignCenter);
    if (text.isEmpty()) {
        text_->hide();
    }
    vl->addWidget(text_, 0, Qt::AlignHCenter);
    vl->addStretch(1);

    timer_ = new QTimer(this);
    timer_->setInterval(interval);
    connect(timer_, &QTimer::timeout, this, &LoadingFrame::changeImage);

    if (!path.isEmpty()) {
        changeImage();
    }
}

void LoadingFrame::setText(const QString& text)
{
    text_->setText(text);
    text_->setVisible(!text.isEmpty());
}

void LoadingFrame::setPath(const QSize& icon_size, const QString& path, int count, int index_width,
                           int interval)
{
    path_ = path;
    count_ = count;
    index_width_ = index_width;
    timer_->setInterval(interval);
    if (path.isEmpty()) {
        image_->setPixmap(QPixmap());
        timer_->stop();
    } else {
        image_->setFixedSize(icon_size);
        changeImage();
        if (count > 0) {
            timer_->start();
        } else {
            timer_->stop();
        }
    }
}

void LoadingFrame::showEvent(QShowEvent* e)
{
    QFrame::showEvent(e);
    if (count_ > 0 && !path_.isEmpty()) {
        timer_->start();
    }
}

void LoadingFrame::hideEvent(QHideEvent* e)
{
    QFrame::hideEvent(e);
    timer_->stop();
};

void LoadingFrame::changeImage()
{
    if (count_ > 0) {
        if (++index_ >= count_) {
            index_ = 0;
        }
        const QString path = path_.arg(index_, index_width_, 10, QChar('0'));
        image_->setPixmap(QPixmap(path));
    } else {
        image_->setPixmap(QPixmap(path_));
    }
}

} // namespace yc
